package cn.rocky.pandacodegen.service;

import cn.rocky.pandacodegen.common.config.GeneratorConfig;
import cn.rocky.pandacodegen.common.utils.SqlHelper;

import cn.rocky.pandacodegen.domain.definition.ColumnDefinition;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 列选择器
 *
 * @author rocky
 * @date 2023-06-28
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public abstract class ColumnSelector {

    private GeneratorConfig generatorConfig;


    /**
     * 获得列定义信息
     *
     * @param tableName 表名
     * @return {@code List<ColumnDefinition>}
     */
    public List<ColumnDefinition> getColumnDefinitions(String tableName) {
        List<Map<String, Object>> resultList = SqlHelper.runSql(this.getGeneratorConfig(), getColumnInfoSQL(tableName));

        List<ColumnDefinition> columnDefinitionList = new ArrayList<ColumnDefinition>(resultList.size());
        // 构建columnDefinition
        for (Map<String, Object> rowMap : resultList) {
            columnDefinitionList.add(buildColumnDefinition(rowMap));
        }

        return columnDefinitionList;
    }

    /**
     * 构建列信息
     * @param rowMap
     * @return
     */
    protected abstract ColumnDefinition buildColumnDefinition(Map<String, Object> rowMap);

    /**
     * 返回查询表字段信息的SQL语句,不同的数据查询表信息不一样
     * 如mysql是DESC tableName
     * @return
     */
    protected abstract String getColumnInfoSQL(String tableName);
}
